package dp.二维数组;

/**
 * https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
 *
 * 题解：https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247493749&idx=1&sn=8c3c56ff2dfd95d608151c7b9d82f0cb&scene=21#wechat_redirect
 */
public class _121_买卖股票的最佳时机 {

    public int maxProfit(int[] prices) {
        int n = prices.length;
        int[][] dp = new int[n][2];

        for (int i = 0; i < n; i++) {
            if (i == 0) {
                dp[i][0] = 0;
                dp[i][1] = -prices[i];
            } else {
                // 这一题因为k=1，只能买一次，
                // dp[i][1][1] = max(dp[i-1][1][1], dp[i-1][0][0] - prices[i]) = max(dp[i-1][1][1], -prices[i])
                dp[i][0] = Math.max(dp[i - 1][1] + prices[i], dp[i - 1][0]);
                dp[i][1] = Math.max(dp[i - 1][1], -prices[i]);
            }
        }

        return dp[n - 1][0];
    }
}
